/**
 * Package name:indi.yangshenhui.tool.weight
 * File name:WeightRandom.java
 * Date:2016年3月19日-下午4:20:46
 * feiniu.com Inc.Copyright (c) 2013-2015 All Rights Reserved.
 *
 */
package indi.yangshenhui.tool.weight;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import com.alibaba.fastjson.JSONObject;

public class WeightRandom {

	public static void main(String[] args) {
		WeightRandom weightRandom = new WeightRandom();

		JSONObject arr = new JSONObject();
		arr.put("key-1", 90);
		arr.put("key-2", 10);
		arr.put("key-3", 1000);

		List<Double> vList = new ArrayList<Double>();
		List<String> kList = new ArrayList<String>();

		for (Entry<String, Object> e : arr.entrySet()) {
			vList.add(Double.valueOf(e.getValue().toString()));
			kList.add(e.getKey());
		}

		Map<String, Integer> stat = new HashMap<String, Integer>();
		for (int i = 0; i < 100000; i++) {
			int weightValue = weightRandom.getWeightRandom(vList);
			if (weightValue < 0) {
				continue;
			}
			System.out.println(weightValue);
			if (stat.get(kList.get(weightValue)) == null) {
				stat.put(kList.get(weightValue), 1);
			} else {
				stat.put(kList.get(weightValue), stat.get(kList.get(weightValue)) + 1);
			}
		}
		System.out.println(stat);
	}

	private double weightArraySum(List<Double> weightArrays) {
		double weightSum = 0;
		for (double weightValue : weightArrays) {
			weightSum += weightValue;
		}
		return weightSum;
	}

	public int getWeightRandom(List<Double> weightArrays) {
		double weightSum = weightArraySum(weightArrays);
		double stepWeightSum = 0;
		for (int i = 0; i < weightArrays.size(); i++) {
			stepWeightSum += weightArrays.get(i);
			if (Math.random() <= stepWeightSum / weightSum) {
				return i;
			}
		}
		return -1;
	}

}
